package com.music.common.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.music.common.dao.IMediaDetails;
import com.music.common.entity.Media;
import com.music.common.errorhandler.DaoException;

public class MediaDetails extends HibernateDaoSupport implements IMediaDetails {

	public MediaDetails() {
	}

	public void save(Media media) {
		getHibernateTemplate().save(media);
	}

	public void update(Media media) {
		getHibernateTemplate().update(media);
	}

	public void delete(Media media) {
		getHibernateTemplate().delete(media);
	}

	public List<Media> getAllMediaDetailByUserName(String userName) throws DaoException {
		try{
			Session session = this.getSession();
			Criteria criteria = session.createCriteria(Media.class);
			Criterion criterion = Restrictions.eq("addedBy", userName);
			criteria.add(criterion);
			List<Media> resultSet = criteria.list();
			return resultSet;
		}catch(Exception ex){
			throw new DaoException(ex);
		}
	}
	
	
	public Integer getMediaCounter() throws DaoException {
		try{
			Integer counter = 0;
			Session session = this.getSession();
			Connection conn = session.connection();
            Statement smt = conn.createStatement();
            ResultSet rs;
            String query = "SELECT MAX(media_id) FROM media;";
            rs = smt.executeQuery(query);
            if (rs.next()) {
            	counter = (Integer) rs.getInt("MAX(media_id)");
            }
            smt.close();
            rs.close();
            conn.close();
			return counter;
		}catch(Exception ex){
			throw new DaoException(ex);
		}
	}
}
